﻿using Hangfire;
using HangFire.Works;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;

namespace HangFire.Common
{
    public static class WorkHelper
    {
        /// <summary>
        /// 反射方法加入队列
        /// </summary>
        /// <param name="backgroundJobs"></param>
        public static void Load(IBackgroundJobClient backgroundJobs) 
        {
            BindingFlags flag = BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod ;
            List<string> MethodList= typeof(OnceWork).GetMethods(flag).Where(c=>c.ReturnType==typeof(void)&&c.GetParameters().Length==0).Select(c=>c.Name).ToList();
            foreach (string me in MethodList)
            {
                MethodCallExpression _methodCallexpP = Expression.Call(typeof(OnceWork).GetMethod(me));
                Expression<Action> _consStringExp = Expression.Lambda<Action>(_methodCallexpP);
                //一次性作业
                backgroundJobs.Enqueue(_consStringExp);
            }
            //周期性作业
            RecurringJob.AddOrUpdate(() => Console.WriteLine("1小时执行一次!"), Cron.Hourly);
            //参数说明 每天0点执行
            RecurringJob.AddOrUpdate(
                () => TimesWork.AutoUpdate(), Cron.Daily(0, 0), TimeZoneInfo.Local
            );
            //只执行一次延迟作业
            var jobId = BackgroundJob.Schedule(() => Console.WriteLine("2小时后执行"), TimeSpan.FromHours(2));
        }
    }
}
